import { APP_BASE_URL } from '@/configs';
import Error404 from '@/pages/error/Error404';
import routes from '@/routes';
import { IRouteItem, IRouteLoader } from '@/routes/RouteType';
import { Suspense } from 'react';
import KeepAlive from 'react-activation';
import {
  RouterProvider,
  createBrowserRouter,
  redirect,
} from 'react-router-dom';

const createRouter = createBrowserRouter;
type IRouteObject = ReturnType<typeof createRouter>;

let routerLoader: IRouteLoader;
let _redirectUrl: string = '/';

export const RouterLoader = (fun: IRouteLoader) => {
  routerLoader = fun;
};

/** 路由处理方式 */
export const generateRouter = (routers: IRouteItem[]) => {
  return routers.map((item: any) => {
    if (item?.children) {
      item.children = generateRouter(item.children);
    }

    item.element = (
      <Suspense fallback={<div>加载中...</div>}>
        {/* 把懒加载的异步路由变成组件装载进去 */}
        {item?.keepAlive ? (
          <KeepAlive id={item?.path} cacheKey={item?.path}>
            <>{item.element}</>
          </KeepAlive>
        ) : (
          item.element
        )}
      </Suspense>
    );
    item.errorElement = <Error404 />;
    item.loader = async (res: any) => {
      if (routerLoader && !item.children) {
        if (routerLoader(res, _redirectUrl)) {
          return res;
        } else {
          return redirect(_redirectUrl);
        }
      }
      return res;
    };

    return item;
  });
};

export const router: IRouteObject = createRouter(generateRouter(routes), {
  basename: APP_BASE_URL,
});

export const RouteRouter = () => {
  return <RouterProvider router={router} />;
};
